<?php

namespace apps\category\backend\controllers;

use Yii;
use apps\category\models\Category;
use apps\category\models\CategorySearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * BackendController implements the CRUD actions for Category model.
 */
class CategoryController extends Controller {

    public function behaviors() {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Category models.
     * @return mixed
     */
    public function actionIndex() {
        $searchModel = new CategorySearch;
        $dataProvider = $searchModel->search(Yii::$app->request->getQueryParams());

        return $this->render('index', [
                    'dataProvider' => $dataProvider,
                    'searchModel' => $searchModel,
        ]);
    }

    /**
     * Displays a single Category model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id) {
        return $this->render('view', [
                    'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Category model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        $model = new Category;
        if ($model->load(Yii::$app->request->post())) {
            $file = \yii\web\UploadedFile::getInstance($model, 'image_url');
            $model->image_url = $file;
            if (!$model->validate()) {
                return $model;
            }
            if ($file) {
                $upload_dir = Yii::$app->basePath . '/web/upload/category/';
                $image_dir = date('Ymd') . '/';
                if (!file_exists($upload_dir . $image_dir)) {
                    mkdir($upload_dir . $image_dir, 0775, true);
                }
                $filename = uniqid() . '.' . $file->getExtension();
                $url = $image_dir . $filename;
                $file->saveAs($upload_dir . $image_dir . $filename);
                $model->image_url = $url;
            }
            if ($model->save()) {
                return $this->redirect(['index']);
            }
        } else {
            $model->loadDefaultValues();
        }
        return $this->render('create', [
                    'model' => $model,
        ]);
    }

    /**
     * Updates an existing Category model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id) {
        $model = $this->findModel($id);
        if ($model->load(Yii::$app->request->post())) {
            $file = \yii\web\UploadedFile::getInstance($model, 'image_url');
            $model->image_url = $file->name;
            if ($model->validate()) {
                if ($file) {
                    $upload_dir = Yii::$app->basePath . '/web/upload/';
                    $uniqid = uniqid();
                    $image_url = substr($uniqid, 0, 3) . '/' . substr($uniqid, 3, 3) . '/' . substr($uniqid, 6, 3) . '/' . substr($uniqid, 9, 4) . '.' . $file->getExtension();
                    $full_path = $upload_dir . $image_url;
                    $image_dir = dirname($full_path);
                    if (!file_exists($image_dir)) {
                        mkdir($image_dir, 0775, true);
                    }
                    $file->saveAs($upload_dir . $image_url);
                    $model->image_url = $image_url;
                }
                if ($model->save()) {
                    return $this->redirect(['index']);
                }
            }
        }
        return $this->render('update', [
                    'model' => $model,
        ]);
    }

    /**
     * Deletes an existing Category model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id) {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Category model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Category the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id) {
        if ($id !== null && ($model = Category::find($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

}
